<template>
  <div class="swiper-container">
    <div v-if="loading" class="loading-state">加载中...</div>
    <div v-else-if="error" class="error-state">数据加载失败，请重试</div>
    <template v-else>
      <div
        class="slides"
        @mousedown="startDrag"
        @touchstart="startDrag"
        @mousemove="onDrag"
        @touchmove="onDrag"
        @mouseup="endDrag"
        @touchend="endDrag"
        @mouseleave="endDrag"
      >
        <div
          v-for="(slide, index) in slides"
          :key="slide.id || index"
          class="slide"
          :class="{
            active: currentIndex === index,
            prev: (currentIndex - 1 + slides.length) % slides.length === index,
          }"
        >
          <div
            class="img"
            :style="{ backgroundImage: `url(${slide.image})` }"
          ></div>
          <!-- <div class="product-panel" :class="{ active: currentIndex === index }">
            <img :src="slide.productImg" alt="Product" class="product-img" />
          </div> -->
        </div>
      </div>

      <div class="pagination">
        <div
          v-for="(_, index) in slides"
          :key="index"
          :class="{ active: currentIndex === index }"
          @click="switchSlide(index)"
        ></div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { get } from "@/utils/request"; // 确保路径正确

// 使用ref定义响应式数据
const slides = ref([]);
const currentIndex = ref(0);
const loading = ref(true);
const error = ref(false);

let timer = null;
const INTERVAL = 5000;

// 拖拽状态（改为X轴）
const isDragging = ref(false);
const startX = ref(0);
const currentX = ref(0);
const dragThreshold = 50; // 拖拽阈值

// 获取轮播图数据
const fetchSlides = async () => {
  try {
    loading.value = true;
    error.value = false;

    // 调用API获取轮播图数据
    const res = await get("/swiper/list");

    if (res.code === 200 && res.data && res.data.length > 0) {
      slides.value = res.data.map((item) => ({
        id: item.id, // 确保每个幻灯片有唯一ID
        image: item.image_url, // 映射接口字段
        title: item.title || "默认标题",
        productImg: item.product_image || "/default-product.png",
        intro: item.description || "默认描述",
      }));
    } else {
      // 处理空数据情况
      error.value = true;
    }
  } catch (err) {
    console.error("获取轮播图数据失败:", err);
    error.value = true;
  } finally {
    loading.value = false;
  }
};

// 轮播控制函数
function startDrag(event) {
  if (event.target.closest(".pagination")) return;
  isDragging.value = true;
  clearInterval(timer);
  const clientX = event.type.includes("touch")
    ? event.touches[0].clientX
    : event.clientX;
  startX.value = clientX;
  currentX.value = 0;
}

function onDrag(event) {
  if (!isDragging.value) return;

  const clientX = event.type.includes("touch")
    ? event.touches[0].clientX
    : event.clientX;

  currentX.value = clientX - startX.value;
  event.preventDefault();
}

function endDrag() {
  if (!isDragging.value) return;

  if (Math.abs(currentX.value) > dragThreshold) {
    if (currentX.value > 0) {
      prevSlide(); // 向右拖拽切换到上一张
    } else {
      nextSlide(); // 向左拖拽切换到下一张
    }
  }

  isDragging.value = false;
  currentX.value = 0;
  resetTimer();
}

function prevSlide() {
  if (slides.value.length === 0) return;
  currentIndex.value =
    (currentIndex.value - 1 + slides.value.length) % slides.value.length;
}

function nextSlide() {
  if (slides.value.length === 0) return;
  currentIndex.value = (currentIndex.value + 1) % slides.value.length;
}

function switchSlide(index) {
  if (slides.value.length === 0) return;
  currentIndex.value = index;
  resetTimer();
}

function resetTimer() {
  clearInterval(timer);
  if (slides.value.length > 1) {
    timer = setInterval(nextSlide, INTERVAL);
  }
}

// 生命周期钩子
onMounted(() => {
  fetchSlides();
});

onBeforeUnmount(() => {
  clearInterval(timer);
});
</script>

<style scoped lang="less">
/* 保持原有样式不变 */
.swiper-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  margin: 0 auto;
  overflow: hidden;
}

.slides {
  position: relative;
  height: 100%;
  cursor: grab;
}

.slides:active {
  cursor: grabbing;
}

.slide {
  position: absolute;
  width: 100%;
  height: 100%;
  transform: translateX(100%); /* 改为水平方向 */
  transition: transform 0.8s ease;
  overflow: hidden;
  .img {
    width: 100%;
    height: 100%;
    background-size: cover;
    background-position: center;
    transition: transform 0.3s ease;
  }
  &:hover{
    .img{
      transform: scale(1.1);
    }
  }
}

.slide.active {
  transform: translateX(0);
  z-index: 2;
}

.slide.prev {
  transform: translateX(-100%); /* 左侧隐藏位置 */
  z-index: 1;
}

.product-panel {
  position: absolute;
  top: auto;
  top: 180px; /* 从顶部移至底部 */
  left: 0;
  width: 100%; /* 宽度铺满 */
  height: auto; /* 高度自适应 */
  padding: 20px;
  box-sizing: border-box;
  backdrop-filter: blur(3px);
  color: white;
  transform: translateY(-100%); /* 改为垂直方向进入 */
  transition: all 0.6s ease;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  opacity: 0;
  display: none;
}

.slide.active .product-panel {
  transform: translateY(0); /* 从底部滑入 */
  opacity: 1;
  transition-delay: 0.5s;
  pointer-events: none;
}

.product-panel h2 {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 20px;
}

.product-img {
  margin: 10px auto 20px auto;
  object-fit: contain;
}

.product-panel p {
  font-size: 20px;
  margin-bottom: 25px;
  line-height: 1.4;
}

.shop-btn {
  width: 157px;
  height: 40px;
  background: transparent;
  border: 1px solid white;
  color: white;
  cursor: pointer;
  transition: background 0.3s;
  margin: 0 auto;
  font-size: 18px;
}

.shop-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.pagination {
  position: absolute;
  bottom: 40px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 12px;
  z-index: 3;
}

.pagination div {
  width: 30px;
  height: 6px;
  border-radius: 3px;
  background: white;
  opacity: 0.5;
  cursor: pointer;
  transition: all 0.3s ease;
  &:hover {
    background: #c5000a;
  }
}

.pagination div.active {
  width: 90px;
  opacity: 1;
}

/* 新增加载和错误状态样式 */
.loading-state,
.error-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 20px 40px;
  border-radius: 5px;
}

.error-state {
  background-color: rgba(255, 0, 0, 0.5);
  cursor: pointer;
}
</style>